package com.example.nonggo.presenter;

import android.util.Log;

import com.example.nonggo.base.BasePresenter;
import com.example.nonggo.bean.PresetQuestionRes;
import com.example.nonggo.contract.HomeContract;
import com.example.nonggo.model.HomeModel;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class HomePresenter extends BasePresenter<HomeContract> implements HomeContract.Presenter  {
   private final HomeModel homeModel;

   public HomePresenter(HomeModel homeModel) {
      this.homeModel = homeModel;
      homeModel.registerCallBack(this);
   }



   private int currentIndex = 0;
   private Disposable disposable;

   @Override
   public void callBackQuestion(PresetQuestionRes data) {
       if (data.getTotal() > 0) {
           // 取消之前的定时任务
           if (disposable != null && !disposable.isDisposed()) {
               disposable.dispose();
           }
   
           // 使用RxJava实现定时任务
           disposable = Observable.interval(0, 5, TimeUnit.SECONDS)
                   .observeOn(AndroidSchedulers.mainThread())
                   .subscribe(aLong -> {
                       // 获取当前项
                       PresetQuestionRes.List list = data.getList().get(currentIndex);
                       getView().getQuestionSuccess(list.getQuestionDetail());
   
                       // 更新索引，循环获取
                       currentIndex = (currentIndex + 1) % data.getList().size();
                   }, throwable -> {
                       Log.e("HomePresenter", "定时任务出错: " + throwable.getMessage());
                   });
       } else {
           Log.e("HomePresenter", "getTotal error");
       }
   }

   @Override
   public void translateText(String text) {
       Log.e( "translateText: ",text );
      getView().jumpToContinueAsk(text);
   }

   public void getQuest(){
      homeModel.getQuestion();
   }

   @Override
   public void destroy() {
       super.destroy();
       // 取消订阅
       if (disposable != null && !disposable.isDisposed()) {
           disposable.dispose();
       }
       homeModel.removeRegisterCallBack();
   }

   public void fileTranslateText(String absolutePath) {
      homeModel.fileTranslateText(absolutePath);
   }
}